package cuit.campus.taskRunning.admin.filter;


import com.alibaba.fastjson.JSON;
import cuit.campus.taskRunning.commons.utils.JwtUtil;
import cuit.campus.taskRunning.commons.utils.RedisCache;

import cuit.campus.taskRunning.user.entry.po.User;
import io.jsonwebtoken.Claims;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        log.info("token:{}",token);
        if(token == null)
        {
            filterChain.doFilter(request,response);
            return;
        }
        String userId = null;
        try {
            Claims claims = jwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException("token非法");
        }
        Object object = redisCache.getCacheObject("user-login" + userId);
        if(object== null)
            throw new RuntimeException("用户未登录");

        //User user = JSON.toJavaObject((com.alibaba.fastjson.JSONObject)object, User.class);
        String jsonString = JSON.toJSONString(object);
        User user = JSON.parseObject(jsonString, User.class);
        //TODO 权限
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,null,null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}
